package com.etc.controller;

import java.time.Duration;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

@RestController
public class CaptchaController {

	Logger logger = LoggerFactory.getLogger(CaptchaController.class);
	@Autowired
	RedisTemplate redisTemplate;

	@GetMapping("captcha")
	public Captcha createCaptcha(HttpServletRequest request) {
		// 定义图形验证码的长、宽、验证码字符数、干扰元素个数
		CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 5, 20);
		// CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
		Captcha result = new Captcha();
		result.setCode(captcha.getCode());
		// 图形验证码写出，可以写出到文件，也可以写出到流
		// String path = request.getRealPath("/") + "/back/admin/images/captcha.gif";
		// captcha.write(path);
		result.setBase64(captcha.getImageBase64Data());
		// 验证图形验证码的有效性，返回boolean值
		// captcha.verify("1234");
		logger.info("code : " + captcha.getCode());
		redisTemplate.opsForValue().set("captcha"+new Date().getTime(), captcha.getCode(), Duration.ofMinutes(3));

		//redisTemplate =>得到所有captcha开头的key
		Set<String> set =  redisTemplate.keys("captcha*");
		
		//
		for (String k : set) {
			System.out.println(k+": "+redisTemplate.opsForValue().get(k));
		}
		return result;
	}
}

class Captcha {
	String code;
	int status = 200;
	String base64 = "";

	public String getBase64() {
		return base64;
	}

	public void setBase64(String base64) {
		this.base64 = base64;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}